import { http } from '../api/axios';
import type { LLMConfig, BrowserConfig, SearchConfig } from '../components/Settings';

interface ConfigResponse {
  status: string;
  config: {
    llm: LLMConfig | null;
    browser: BrowserConfig | null;
    search: SearchConfig | null;
  };
}

// 默认配置
const defaultConfig  = {
  llm: {
    base_url: 'https://api.deepseek.com/v1',
    api_key: '',
    model: 'deepseek-chat',
    temperature: 0,
    max_tokens: 4086
  },
  browser: {
    headless: false,
    disable_security: true,
    chrome_instance_path: '',
    proxy_enabled: false,
  },
  search : {
    engine: 'Baidu',
    max_retries: 3,
    retry_delay: 60,
  }
};

// 获取配置
export const getConfig = async () => {
  try {
    const response = await http.get<ConfigResponse>('/execution/config/status');
    
    // 使用默认值填充缺失的配置
    return {
      status: response.status,
      config: {
        llm: { ...defaultConfig.llm, ...response.config.llm },
        browser: { ...defaultConfig.browser, ...response.config.browser },
        search: { ...defaultConfig.search, ...response.config.search }
      }
    };
  } catch (error) {
    console.error('获取配置失败:', error);
    // 如果请求失败，返回默认配置
    return {
      status: 'error',
      config: defaultConfig
    };
  }
};

// 保存配置
export const saveConfig = async (config: {
  llm?: LLMConfig;
  browser?: BrowserConfig;
  search?: SearchConfig;
}) => {
  try {
    const response = await http.post<{ status: string }>('/execution/config/save', config);
    return response;
  } catch (error) {
    console.error('保存配置失败:', error);
    throw error;
  }
}; 